import styled from '@emotion/styled';

import { colors } from '@/config/theme';
import { NodeResultItem, useNodeResults } from '@/store/node-results';

import { ExecLoggerDetail } from './detail';

interface NodeLoggerProps {
  nodeId: string;
}

const NodeExecLoggerDiv = styled.div`
  box-shadow: 0 0 8px ${colors.gray[300]};
`;
/**
 * 节点执行日志
 */
export const NodeExecLogger = memo<NodeLoggerProps>((props) => {
  const resultsStore = useNodeResults();
  const [focusResult, setFocusResult] = useState<NodeResultItem | null>(null);

  const results = resultsStore.resultsOfList?.filter((item) => item.nodeId === props.nodeId) || [];

  if (!results.length) return null;

  return (
    <>
      <NodeExecLoggerDiv
        onClick={(e) => e.stopPropagation()}
        className="node-logger flex flex-col gap-8 absolute top-48 left-[50%] -translate-x-[50%] w-200 px-12 py-8 bg-white rounded-8">
        {results.map((item) => {
          return (
            <div className="result-item" key={item.execId}>
              <div>
                <label className="text-14">执行状态: </label>
                {item.errorMsg ? (
                  <span className="text-14 !text-red">错误</span>
                ) : (
                  <span className="text-14 !text-green-600">成功</span>
                )}
              </div>
              <div>
                <label className="text-14">执行耗时: </label>
                <strong className="text-value-14_bold">{(item.endTime || 0) - (item.startTime || 0)} ms</strong>
              </div>
              <div className="input-params">
                <label className="text-14">执行次数: </label>
                <strong className="text-value-14_bold">{item.execResult?.length || 1}</strong>
              </div>

              {!!item.execResult?.length || item.errorMsg ? (
                <div className="output mt-4 text-center">
                  <span
                    onClick={() => {
                      setFocusResult(item);
                    }}
                    className="text-14 !text-blue-500 cursor-pointer underline">
                    查看详细结果
                  </span>
                </div>
              ) : null}
            </div>
          );
        })}
      </NodeExecLoggerDiv>

      <ExecLoggerDetail
        nodeId={props.nodeId}
        focusResult={focusResult}
        onClose={() => {
          setFocusResult(null);
        }}
      />
    </>
  );
});
